package edu.gatech.cc.CFAWaffleFriesWheresMyStuff.gui;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import edu.gatech.cc.CFAWaffleFriesWheresMyStuff.R;
import edu.gatech.cc.CFAWaffleFriesWheresMyStuff.common.Datastore.UserDoesNotExistException;
import edu.gatech.cc.CFAWaffleFriesWheresMyStuff.common.DatastoreFactory;
import edu.gatech.cc.CFAWaffleFriesWheresMyStuff.common.User;
import edu.gatech.cc.CFAWaffleFriesWheresMyStuff.common.UserManager;

public class SearchActivity extends Activity {

	private User _user;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_search);
		Bundle extras = getIntent().getExtras();
		
		String username = extras.getString("user", "");
		UserManager userManager = new UserManager(DatastoreFactory.getDatastore(getApplicationContext()));
		try {
			_user = userManager.getUser(username);
		} catch (UserDoesNotExistException e) {
			e.printStackTrace();
		}
		
		final EditText nameText = (EditText)findViewById(R.id.searchItemByName_textField);
		final Spinner categorySpinner = (Spinner)findViewById(R.id.searchItem_itemCategorySpinner);
		
		((Button)findViewById(R.id.searchButton)).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				String name = nameText.getText().toString();
				if(name.isEmpty())
					name = null;
				String category;
				int selected = categorySpinner.getSelectedItemPosition();
				if(selected > 0)
					category = getResources().getStringArray(R.array.item_categories_pickOne)[selected];
				else
					category = null;
				
				Intent i = new Intent(getApplicationContext(), ItemListActivity.class);
				i.putExtra("loggedIn", _user.getUsername());
				i.putExtra("itemName", name);
				i.putExtra("category", category);
				i.putExtra("title", "Search Results");
				startActivity(i);
			}
		});
		
		((Button)findViewById(R.id.cancelButton)).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_search, menu);
		return true;
	}

}
